using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartLink.Infrastructure
{
    /// <summary>
    /// 地图帮助类
    /// </summary>
    public class MapHelper
    {
        private const double EARTH_RADIUS = 6378.137;//地球半径
        private static double rad(double d)
        {
            return d * Math.PI / 180.0;
        }

        /// <summary>
        /// 计算两个GPS点之间的距离（km）
        /// </summary>
        /// <param name="lat1">点1纬度</param>
        /// <param name="lng1">点1经度</param>
        /// <param name="lat2">点2纬度</param>
        /// <param name="lng2">点2经度</param>
        /// <returns>距离（km）</returns>
        public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
        {
            double radLat1 = rad(lat1);
            double radLat2 = rad(lat2);
            double a = radLat1 - radLat2;
            double b = rad(lng1) - rad(lng2);

            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
            s = s * EARTH_RADIUS;
            s = Math.Round(s * 10000) / 10000;
            return s;
        }

        /// <summary>
        /// 判断给定经纬坐标是否在指定经纬坐标多边形内，在边上也属于“包含”
        /// </summary>
        /// <param name="poly">构成指定多边形的经纬坐标集合</param>
        /// <param name="point">要判断的经纬坐标</param>
        /// <returns>该经纬坐标是否在指定经纬坐标多边形内</returns>
        public static bool IsPointInPolygon(IList<Loc> poly, Loc point)
        {
            int i, j;
            bool c = false;
            for (i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
            {
                if ((((poly[i].Lat <= point.Lat) && (point.Lat < poly[j].Lat))
                        || ((poly[j].Lat <= point.Lat) && (point.Lat < poly[i].Lat)))
                        && (point.Lng < (poly[j].Lng - poly[i].Lng) * (point.Lat - poly[i].Lat)
                            / (poly[j].Lat - poly[i].Lat) + poly[i].Lng))

                    c = !c;
            }
            return c;
        }
    }

    /// <summary>
    /// 经纬坐标
    /// </summary>
    public struct Loc
    {
        /// <summary>
        /// 经度
        /// </summary>
        public double Lng { get; set; }
        /// <summary>
        /// 纬度
        /// </summary>
        public double Lat { get; set; }
    }
}
